<template>
  <div style="height:100%">
    <baleTable
      :tableData="tableData"
      :tableHead="tableHead"
      :isSearch="false"
      :isTableRowClick="true"
      :tableLoading="tableLoading"
      :page="page"
      @pageSizeChange="pageSizeChange"
      @handleCurrentChange="handleCurrentChange"
      @searchMethods="searchMethods"
      @tableSortChange="tableSortChange"
      @handleRowClick="handleRowClick"
      ref="baleTable"
    >
      <template #headLeft>
        <div
          class="ml10 tableStats-btn tableStats-btn-active"
          @click="showDialog()"
        >
          添加
        </div>
      </template>

      <template #caozuo="{ scope }">
        <el-button type="primary" size="mini" @click="showDialog(scope.row)"
          >编辑</el-button
        >
        <el-button type="danger" size="mini" @click="delRole(scope.row)"
          >删除</el-button
        >
      </template>
    </baleTable>

    <el-dialog
      class="dialog"
      :title="editID ? '修改角色' : '添加角色'"
      :visible.sync="editFormVisible"
      :close-on-click-modal='false'
      :close-on-press-escape='false'
      center >
      <el-form autocomplete="off" ref="roleForm"  label-width="110px" :model="editForm">
        <el-form-item label="角色名称" prop="name" :rules="{required: true,message: '请输入角色名称',trigger: 'blur'}">
          <el-input
            size="medium"
            v-model="editForm.name"
            auto-complete="off"
            placeholder="请输入角色名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="角色显示名称" prop="display_name" :rules="{required: true,message: '请输入角色显示名称',trigger: 'blur'}">
          <el-input
            size="medium"
            v-model="editForm.display_name"
            auto-complete="off"
            placeholder="请输入角色显示名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="描述" :rules="{required: true,message: '请输入角色描述',trigger: 'blur'}">
          <el-input
            type="textarea"
            v-model="editForm.description"
            placeholder="请输入角色描述"
          ></el-input>
        </el-form-item>

      </el-form>
      <div v-loading="treeLoading">
        <h3 class="mb10">角色拥有权限：</h3>
        <el-tree ref="tree" node-key="id" :default-checked-keys="checkData" :props="defaultProps" :data="treeData" show-checkbox>
        </el-tree>
      </div>
      <div slot="footer">
        <el-button @click="editFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit" :loading='btnLoading' >确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { Apirole, ApiroleDel,ApiroleAdd,ApiroleEdit, ApirolePermission, ApirolepermissionPut } from "@a";
import { tableHead } from "./config";
import { debounce } from "@u/index"
export default {

  data() {
    return {
      tableHead,
      tableData: [],
      page: {
        page: 1,
        size: 25,
        total: 0,
      },
      tableLoading: false,
      searchParams: {},
      sortParams: {},
      editFormVisible: false,
      btnLoading: false,
      treeLoading: false,
      editForm: {
        name: "",
        display_name: "",
        description: ""
      },
      treeData: [],
      checkData: [],
      defaultProps:{
        children: 'sub_permission',
        label: 'name'
      },
      editID: ""
    };
  },
  mounted() {
    this.getTableData();
  },
  methods: {
    submit: debounce(function() {
      this.$refs.roleForm.validate((valid)=>{
        if(valid){
          this.btnLoading = true
          const permissions = this.$refs.tree.getCheckedNodes(false,true).map(item=>item.id)
          if(this.editID){
            this.putData(permissions)
          }else {
            this.addData(permissions)
          }
        }
      })
    },800,true),
    putData(permissions) {
      ApiroleEdit(this.editForm,this.editID).then(res => {
        this.putPermission(permissions,this.editID)
      }).catch(_=>{
        this.btnLoading = false
      })
    },
    addData(permissions) {
      ApiroleAdd(this.editForm).then(res => {
        this.putPermission(permissions,res.data.id)
      }).catch(_=>{
        this.btnLoading = false
      })
    },
    putPermission(permissions,id) {
      ApirolepermissionPut({permissions},id).then(res => {
        this.$message.success("操作成功！")
        this.editFormVisible = false
        this.getTableData();
      }).finally(_=>{
        this.btnLoading = false
      })
    },
    // 删除
    delRole(val) {
      this.$confirm("是否删除该角色?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        center: true,
        type: "warning",
      })
        .then((res) => {
          ApiroleDel(val.id).then((res) => {
            this.$message.success("操作成功！");
            this.getTableData();
          });
        })
        .catch((err) => {

        });
    },

    //编辑
    showDialog(row=null) {
      const parmas = {role_id: 0}
      if(row) {
        this.editID = parmas.role_id = row.id
      }else{
        this.editID = null
        row = {}
      }
      for (const key in this.editForm) {
        this.editForm[key] = row[key]
      }
      this.editFormVisible = true
      this.getTreeData(parmas)
    },

    getTreeData(parmas) {
      this.treeLoading = true
      ApirolePermission(parmas).then(({data}) => {
        this.treeData = data
        let checkData = []
        function getId (data){
          data.forEach(ele =>{
            if(ele.checked === 1){
              if(ele.sub_permission.length === 0){
                checkData.push(ele.id)
              }else{
                getId(ele.sub_permission)
              }
            }
          })
        }
        getId(data)
        this.checkData = checkData
        this.treeLoading = false
      })
    },
    getTableData(params = {}) {
      let postParams = {
        ...params,
        ...this.searchParams,
        ...this.sortParams,
        ...this.page,
      };
      this.tableLoading = true;
      Apirole(postParams).then((res) => {
        let { data, page } = res;
        this.tableData = data;
        this.page.total = page.total;

        this.tableLoading = false;
      });
    },
    searchMethods(params) {
      this.searchParams = {};
      this.page.page = 1;
      this.searchParams = params;
      this.getTableData();
    },
    pageSizeChange(val) {
      this.page.size = val;
      this.getTableData();
    },
    handleCurrentChange(val) {
      this.page.page = val;
      this.getTableData();
    },
    tableSortChange(params) {
      if (params.sort_str) {
        this.sortParams = { ...this.sortParams, ...params };
      } else {
        delete this.sortParams.sort_str;
        delete this.sortParams.sort_order;
      }
      this.page.page = 1;
      this.getTableData();
    },
    handleRowClick(params) {},
  },
};
</script>

<style lang="less" scoped>

</style>
